<?php

namespace app\common\model;


use app\common\exception\ApiException;

class User extends BaseModel {
    public function saveUser($data) {
        $openID = empty($data['openid']) ? $data['openId'] : $data['openid'];
        $user   = self::get(['openid' => $openID]);
        if ($user) {
            $data['status'] = !empty($data['nickName']) ? config('code.status_show') : 0;
            $this->allowField(true)->save($data, ['id' => $user->id]);
            return $user->id;
        } else {
            $data['status'] = config('code.status_unshow');
            $this->allowField(true)->save($data);
            return $this->getLastInsID();
        }
    }

    public function getUserList($condition = [], $from = 0, $size = 10, $order = ['id' => 'desc']) {
        $result = $this->where($condition)
            ->field(['id', 'nickName', 'gender', 'city', 'province', 'avatarUrl', 'publish_count', 'login_count', 'forbidden', 'update_time'])
            ->limit($from, $size)
            ->order($order)
            ->select();
        if (!$result) {
            throw new ApiException('没有数据了亲', 200, 1);
        }
        $total        = $this->where($condition)->count();
        $arr['list']  = $result;
        $arr['total'] = $total;
        return $arr;
    }

    public function getCityAndProvince() {
        try {
            $arr['city']     = model('User')->field('city')->group('city')->select();
            $arr['province'] = model('User')->field('province')->group('province')->select();
        } catch (\Exception $e) {
            throw new ApiException($e->getMessage(), 400, 1);
        }
        return $arr;
    }

    public function getUserInfo($id) {
        $result = $this->field(['nickName', 'avatarUrl', 'status', 'hasUnRead'])
            ->where(['id' => $id])
            ->find();
        if (!$result) {
            throw new ApiException('获取用户数据失败', 200, 1);
        }
        if ($result->status == 0) {
            throw new ApiException('用户没授权', 200, 11);
        }
        return $result;
    }
}